package com.luyang.platform.auth.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 授权服务器配置
 *
 * @author lu_yang
 */
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfiguration {

    private static final String CUSTOM_CONSENT_PAGE_URI = "/oauth2/consent";

    private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfiguration.class);

    /**
     * Authorization server 集成 <br>
     * 定义 Spring Security 的拦截器链
     *
     * @param http http
     * @return org.springframework.security.web.SecurityFilterChain
     * @author lu_yang
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public @Bean SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {

        // 授权服务器配置
        var authorizationServerConfigurer =
            new OAuth2AuthorizationServerConfigurer<HttpSecurity>();

        //  把自定义的授权确认URI加入配置
        authorizationServerConfigurer
            .authorizationEndpoint(authorizationEndpoint ->
                authorizationEndpoint.consentPage(CUSTOM_CONSENT_PAGE_URI));

        RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();

        // 拦截 授权服务器相关的请求端点
        return http
            .requestMatcher(endpointsMatcher)
            .authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated())
            // 忽略掉相关端点的csrf
            .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
            // 应用 授权服务器的配置
            .apply(authorizationServerConfigurer)
            .and()
            // 开启form登录
            .formLogin()
            .and()
            .build();
    }
}
